package com.epam.player.vkapi.authentication;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.epam.player.vkapi.ApllicationContext;
import com.epam.player.vkapi.common.APIConstant;
import com.epam.player.vkapi.exceptions.CredentialsWrongException;
import com.epam.player.vkapi.exceptions.TemporarilyUnavailableServiceException;
import com.epam.player.vkapi.model.ApplContextTypes;

public class ConnectionManager {

	private static final String VK_LOGIN = "http://vk.com/login.php";
	private static final Logger LOG = Logger.getLogger(ConnectionManager.class);

	public Connection createConnection(Map<String, String> data)
			throws CredentialsWrongException,
			TemporarilyUnavailableServiceException {

		Connection connection = Jsoup.connect(VK_LOGIN).data(data)
				.userAgent("Mozilla").cookie("auth", "token").timeout(5000);
		Response response;
		try {
			LOG.info("Try to connect with " + VK_LOGIN);
			response = connection.execute();
			LOG.info("Succes connect to " + VK_LOGIN);
			LOG.info("Add  ApplContextTypes.DATA to ApllicationContext");
			ApllicationContext.addToContext(ApplContextTypes.DATA, data);
		} catch (IOException e) {
			LOG.error("Temporarily Unavailable Service Exception", e);
			throw new TemporarilyUnavailableServiceException();
		}
		String html = response.body();
		String hash = html;
		Document document = Jsoup.parse(html);
		try {
			html = document.getElementsByTag("script").get(0).toString();
		} catch (IndexOutOfBoundsException e) {
			LOG.error("Temporarily Unavailable Service Exception", e);
			throw new TemporarilyUnavailableServiceException();
		}
		String idUser = null;
		if (html.indexOf("id: ") != -1) {
			idUser = html.substring(html.indexOf("id: ") + 4,
					html.indexOf(",", html.indexOf("id:")));
			LOG.info("Add to data ID_USER = " + idUser);
			data.put(APIConstant.ID_USER, idUser);
			String hashAudioStatus = getUserHashForAddMusic(hash);
			LOG.info("Add to data HASH_AUDIO_USER = " + hashAudioStatus);
			data.put(APIConstant.HASH_AUDIO_USER, hashAudioStatus);
		} else {
			LOG.error("Error credentials. Mail or password is wrong.");
			throw new CredentialsWrongException();
		}
		return connection;
	}

	private String getUserHashForAddMusic(String body) {
		String findHashKey = "audioStatusUpdate('";
		int startHashPos = body.indexOf(findHashKey);
		int endHashPos = body.indexOf("');\"", startHashPos);
		String hash = body.substring(startHashPos + findHashKey.length(),
				endHashPos);
		return hash;
	}
}
